package com.liam.lotterysystem.common.pojo;

import com.liam.lotterysystem.common.errorcode.ErrorCode;
import com.liam.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * @Author: LiamLMK
 * @CreateTime: 2024-10-10
 * @Description:
 * @Version: 1.0
 */

/**
 * 序列化: 实现了 Serializable 接口,
 * 使得CommonResult<T>对象可以被序列化为多种格式, 如 JSON 或 XML, 方便网络传输
 * @param <T>
 */
@Data
public class CommonResult<T> implements Serializable {

    // 返回的错误码
    private Integer code;

    // 正常返回数据
    private T data;

    // 错误码描述
    private String msg;

    public static <T> CommonResult<T> success(T data) {
        CommonResult<T> result = new CommonResult<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = "";
        return result;
    }

    public static <T> CommonResult<T> error(Integer code, String msg) {
        Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "code并非错误异常");
        CommonResult<T> result = new CommonResult<>();
        result.code = code;
        // 错误码无需返回data
        result.msg = msg;
        return result;
    }

    public static <T> CommonResult<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }
}
